package research.xmpp;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class XMPPAsync {
	
	private BlockingDeque<String> result;
	
	private XMPPConnection connection;
	
	public XMPPAsync() {
		result = new LinkedBlockingDeque<String>();
		connection = new XMPPConnection("zezinho");
		try {
			connection.connect();
			connection.login("server1", "s1");
		} catch (XMPPException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public String talk() throws InterruptedException {
		ChatManager chatManager = connection.getChatManager();
		Chat chat = chatManager.createChat("client1@zezinho", new MessageListener() {
			@Override
			public void processMessage(Chat chat, Message message) {
				result.add(message.getBody());				
			}
		});
		
		try {
			chat.sendMessage("Hi!");
		} catch (XMPPException e) {
			throw new RuntimeException(e);
		}
		
		return result.pollFirst(5, TimeUnit.SECONDS);
	}

	
	public static void main(String[] args) throws InterruptedException {
		XMPPAsync xmpp = new XMPPAsync();
		System.out.println("> Connected...");
		System.out.println("> Send msg...");
		System.out.println(xmpp.talk());
		System.out.println("> over.");
		
	}
}
